package org.jeecg.modules.middleware.rabbitmq.gas;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.wlhy.gas.entity.HyShippingNoteGas;
import org.jeecg.modules.wlhy.gas.service.IHyShippingNoteGasService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 万金油
 */
@Service
public class GasMqUtil {

    private static RabbitTemplate gasrt;

    @Autowired
    public GasMqUtil(RabbitTemplate template) {
        template.setEncoding("UTF-8");
        //设置手工ack确认
        template.setMandatory(true);
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String s) {
                if (!ack) {
                    try {
                        String jsonData = new String(correlationData.getReturnedMessage().getBody(), "utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                try {
                    String jsonData = new String(message.getBody(), "utf-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        gasrt = template;
    }

    public static void recharge(String id ){
        JSONObject jo = new JSONObject();
        jo.put("channel", "1");
        jo.put("msg", id);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        gasrt.convertAndSend("gasExchange", "gas", jo.toJSONString(),
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                }
                , correlationData);
    }

    public static void back(String id){
        JSONObject jo = new JSONObject();
        jo.put("channel", "2");
        jo.put("msg", id);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        gasrt.convertAndSend("gasExchange", "gas", jo.toJSONString(),
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                }
                , correlationData);
    }

}
